package cn.itcast.travel.web.servlet;

import cn.itcast.travel.domain.ResultInfo;
import cn.itcast.travel.domain.User;
import cn.itcast.travel.service.UserService;
import cn.itcast.travel.service.impl.UserServiceImpl;
import cn.itcast.travel.util.UuidUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();

    public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, InvocationTargetException, IllegalAccessException {
        //这个是我们在注册页面写入的
        String check = request.getParameter("check");
        HttpSession session = request.getSession();
        //这个是我们后台CheckCodeServlet生成的
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");

        if (check.equalsIgnoreCase(checkcode_server)) {

            Map<String, String[]> map = request.getParameterMap();
            User user = new User();
            //邮箱是否已激活
            user.setStatus("N");

            //激活邮件的标识码,必须要保证唯一
            user.setCode(UuidUtil.getUuid());

            //把map里的接收到的表单项的值，封装到user里面去
            BeanUtils.populate(user, map);

            ResultInfo info = userService.regist(user);

            //把info变成json数据
            writeValue(response, info);
        } else {
            ResultInfo info = new ResultInfo();
            info.setFlag(false);
            info.setErrorMsg("验证码错误");
            writeValue(response, info);
        }
    }

    public void acitve(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, InvocationTargetException, IllegalAccessException {
        String code = request.getParameter("code");
        boolean flag = userService.active(code);
        if(flag){
            response.sendRedirect(request.getContextPath()+"/login.html");
        }else{
            response.setContentType("text/html;charset=utf8");
            response.getWriter().write("激活失败，请重新注册");
        }
    }

}
